﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EComAssignment.Models;
using System.Dynamic;
using System.Web.Routing;
using EComAssignment.Filter;
using System.Data.Objects;

namespace EComAssignment.Controllers
{
    public class MainController : Controller
    {
        //
        // GET: /Main/
                
        public ActionResult Index2(int? pageNum)
        {            
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 12;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var productList = (from p in ctx.Products
                               orderby p.sell_start_date descending
                               where p.is_selling.Equals(true) && p.capacity > 0
                               select p);
            foreach (var rs in productList)
            {
                if (rs.promotion_ID.HasValue)
                {
                    if (System.DateTime.Now < rs.Promotion.start_date || rs.Promotion.end_date < System.DateTime.Now)
                    {
                        rs.Promotion = null;
                    }
                }
            }
            ViewBag.maxPage = (productList.Count()-1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            ViewBag.list = productList.Skip(skipNum).Take(maxProNum);                        
            return View();
        }
                
        public ActionResult show()
        {            
            string group_name = Request.QueryString["group"];
            int id = 0;
            try
            {
                id = Int32.Parse(Request.QueryString["id"]);
            }
            catch (Exception) { }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var productList = (from p in ctx.Products
                               orderby p.sell_start_date descending
                               where p.is_selling.Equals(true) && p.category_ID == id && p.group_name.Equals(group_name)
                               select p);
            if (id > 0)
            {
                ViewBag.cateName = (from c in ctx.Categories
                                    where c.ID == id
                                    select c.name).First().ToString();
                if (group_name == null)
                {
                    productList = (from p in ctx.Products
                                   orderby p.sell_start_date descending
                                   where p.is_selling.Equals(true) && p.category_ID == id
                                   select p);        
                }
            }else if (id == 0)
            {
                productList = (from p in ctx.Products
                               orderby p.sell_start_date descending
                               where p.is_selling.Equals(true) 
                               select p);
            }
            foreach (var rs in productList)
            {
                if (rs.promotion_ID.HasValue)
                {
                    if (System.DateTime.Now < rs.Promotion.start_date || rs.Promotion.end_date < System.DateTime.Now)
                    {
                        rs.Promotion = null;
                    }
                }
            }
            ViewBag.list = productList;            

            return View();
        }

        public ActionResult ShowCategories()
        {
            getCategories2();
            return View();
        }

        public ActionResult viewProduct()
        {
            
            int id = 0;
            try
            {
                id = Int32.Parse(Request.QueryString["proID"]);
            }
            catch (Exception) { }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var product = (from p in ctx.Products                               
                               where p.ID == id && p.is_selling == true
                               select p).SingleOrDefault();
            ViewBag.product = product;
            if (product == null)
            {
                Response.Redirect("/Main/index2");
            }
            ViewBag.cateName = (from c in ctx.Categories
                                where c.ID == product.category_ID
                                select c.name).First().ToString();
            var rate = (from pr in ctx.Promotions
                             where pr.ID == product.promotion_ID && pr.start_date <= System.DateTime.Now && System.DateTime.Now <= pr.end_date
                             select pr.rate).SingleOrDefault();
            if(rate > 0)
            {
                ViewBag.rate = rate;
                ViewBag.newPrice = product.price / 100 * (100 - rate);
            }
            return View();
        }
                
        public ActionResult search()
        {
            
            string key = Request.QueryString["key"];
            if (key == null)
            {
                key = "";
            }
            key = MainModel.ConvertToVietnameseNotSignature(key).ToLower();
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var result = ctx.Products.Where(p => p.ID == -1);
            var productList = ctx.Products.Where(p => p.is_selling == true && p.capacity > 0);
            foreach (var rs in productList)
            {
                if (MainModel.ConvertToVietnameseNotSignature(rs.name).ToLower().Contains(key))
                {
                    result = result.Union(ctx.Products.Where(p => p.ID == rs.ID));
                }
            }
            /*remove promotion not available*/
            foreach (var rs in result)
            {
                if (rs.promotion_ID.HasValue)
                {
                    if (System.DateTime.Now < rs.Promotion.start_date || rs.Promotion.end_date < System.DateTime.Now)
                    {
                        rs.Promotion = null;
                    }
                }                
            }
            
            ViewBag.productList = result;
            return View();
        }

        public ActionResult advanceSearch()
        {
            getCategories2();
            return View();
        }
        
        [HttpPost]
        public ActionResult advanceSearchClick()
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            
            /*get the list of category*/
            string[] cateIDList = Request.Form["categoriesIDList"].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            HashSet<string> groupSet = new HashSet<string>();
            foreach (string c in cateIDList)
            {
                int ca = 0;
                try
                {
                    ca = Int32.Parse(c.Trim());
                }
                catch (Exception) { }
                var pro = (from p in ctx.Products
                           where p.category_ID == ca
                           select p.group_name).Distinct();
                foreach (var g in pro) { groupSet.Add(g); }
            }
            /*get the list of group name*/
            string[] groupList = Request.Form["groupList"].Split(new char[]{','},StringSplitOptions.RemoveEmptyEntries);
            foreach (string g in groupList) { groupSet.Add(g); }
            /*create an empty table*/
            var proList = (from p in ctx.Products where p.ID == 0 select p);
            foreach (var groupName in groupSet)
            {
                var pro = (from p in ctx.Products
                               where p.group_name.Equals(groupName)
                               select p);
                proList = proList.Union(pro);
            }

            /*search by name*/
            var result = (from p in ctx.Products where p.ID == 0 select p);
            var key = MainModel.ConvertToVietnameseNotSignature(Request.Form["key"]).ToLower();
            foreach(var rs in proList)
            {
                if (MainModel.ConvertToVietnameseNotSignature(rs.name).ToLower().Contains(key))
                {
                    result = result.Union(proList.Where(p => p.ID == rs.ID));
                }
            }

            /*search by price*/
            decimal minPrice = 0;
            try
            {
                minPrice = decimal.Parse(Request.Form["fromPrice"]);
            }
            catch (Exception) { }
            //search min price
            result = result.Where(x => x.price >= minPrice);
            decimal maxPrice = 0;
            try
            {
                maxPrice = decimal.Parse(Request.Form["toPrice"]);
            }
            catch (Exception) 
            {
                maxPrice = (from p in ctx.Products
                            select p.price).Max();
            }            
            //search max price
            result = result.Where(x => x.price <= maxPrice && x.is_selling == true && x.capacity > 0);

            ViewBag.productList = result;
            return View("search");
        }

        private void getCategories2()
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            Dictionary<int, IQueryable<string>> list = new Dictionary<int, IQueryable<string>>();
            Dictionary<int, string> list2 = new Dictionary<int, string>();
            var category = (from c in ctx.Categories
                            select new {c.ID, c.name});
            foreach(var cate in category)
            {
                var group = (from p in ctx.Products
                             where p.category_ID == cate.ID
                             select p.group_name).Distinct();                
                list.Add(cate.ID, group);
                list2.Add(cate.ID, cate.name);
            }
            ViewBag.categoryList2 = list;
            ViewBag.categoryList2Name = list2; 
        }

        public ActionResult CartAmount()
        {
            return View();
        }

        public ActionResult show2(int? pageNum)
        {
            string group_name = Request.QueryString["group"];
            ViewBag.group_name = group_name;
            int id = 0;
            try
            {
                id = Int32.Parse(Request.QueryString["id"]);
            }
            catch (Exception) { }
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var productList = (from p in ctx.Products
                               orderby p.sell_start_date descending
                               where p.is_selling.Equals(true) && p.category_ID == id && p.group_name.Equals(group_name) && p.capacity > 0
                               select p);
            if (id > 0)
            {
                ViewBag.cateName = (from c in ctx.Categories
                                    where c.ID == id
                                    select c.name).First().ToString();
                if (group_name == null || group_name.Length==0)
                {
                    productList = (from p in ctx.Products
                                   orderby p.sell_start_date descending
                                   where p.is_selling.Equals(true) && p.category_ID == id && p.capacity > 0
                                   select p);
                }
            }
            else if (id == 0)
            {
                productList = (from p in ctx.Products
                               orderby p.sell_start_date descending
                               where p.is_selling.Equals(true) && p.capacity > 0
                               select p);
            }
            ViewBag.id = id;
            foreach (var rs in productList)
            {
                if (rs.promotion_ID.HasValue)
                {
                    if (System.DateTime.Now < rs.Promotion.start_date || rs.Promotion.end_date < System.DateTime.Now)
                    {
                        rs.Promotion = null;
                    }
                }
            }

            if(pageNum == null){pageNum = 1;}
            int maxProNum = 8;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (productList.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            ViewBag.list = productList.Skip(skipNum).Take(maxProNum);            

            return View();
        }

        public ActionResult TopMenu()
        {
            return View();
        }

        public ActionResult viewCategory(int? id, int? proID, string proName)
        {
            
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cate = (from c in ctx.Categories
                           where c.ID == id
                           select c).SingleOrDefault();
            
            if (cate == null)
            {
                return RedirectToAction("Index2","Main");
            }
            ViewBag.category = cate;
            ViewBag.proID = proID;
            ViewBag.proName = proName;
            return View();
        }

        public ActionResult ModuleFeedback()
        {
            
            string username = Session["username"] != null ? Session["username"].ToString() : null;
            string email = "";
            if (username != null)
            {
                DataClasses1DataContext ctx = new DataClasses1DataContext();
                var accEmail = (from a in ctx.Accounts
                             where a.username == username
                             select a.email).SingleOrDefault();
                email = accEmail;
            }
            return View((object)email);
        }

        [HttpPost]
        public ActionResult FeedbackClick(string email,string title, string body)
        {
            MainModel.feedbackHandler(email, title, body);
            return null;
        }

        public ActionResult SliderShow()
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var slider = (from s in ctx.Sliders
                          select s);
            if (slider.Count() == 0) { slider = null; }
            return View(slider);
        }

        public ActionResult CommentView(int proID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var cmtList = (from c in ctx.Comments
                       where c.is_reply == false && c.product_ID == proID
                       orderby c.post_date descending
                       select c);
            Dictionary<Comment, IOrderedQueryable> model = new Dictionary<Comment, IOrderedQueryable>();
            foreach (var cmt in cmtList)
            {
                var rl = (from r in ctx.Comments
                          where r.is_reply == true && r.reply_ID == cmt.ID && r.product_ID == proID
                          orderby r.post_date ascending
                          select r);
                model.Add(cmt, rl); //foreach (var t in rl) { t.body}
            }
            return View(model);
        }

        [HttpPost]
        public ActionResult postComment(string username, int proID, string body, bool isReply, int? replyID)
        {
            MainModel.saveComment(username, proID, body, isReply, replyID);
            RouteValueDictionary data = new RouteValueDictionary();
            data.Add("proID", proID);
            return RedirectToAction("CommentView", "Main", data);
        }

        public ActionResult RatingView(int proID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var rateList = ctx.Ratings.Where(r => r.product_ID == proID).OrderByDescending(r => r.rate_date);
            return View(rateList);// foreach (var r in rateList) {r. }
        }

        [HttpPost]
        public ActionResult RatingClick(string username,int proID, int rate, string opinion)
        {
            MainModel.saveRating(username, proID, rate, opinion);
            RouteValueDictionary data = new RouteValueDictionary();
            data.Add("proID", proID);
            return RedirectToAction("RatingView","Main",data);
        }

        public ActionResult ratePoint(int proID)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var rateList = ctx.Ratings.Where(r => r.product_ID == proID);
            int count = 0;
            decimal sum = 0;
            foreach(var rate in rateList)
            {
                count++;
                sum += rate.rate;
            }
            if (count == 0) { return View(0); }
            int width = Convert.ToInt32(13 * sum / count);
            return View(width);
        }

        public ActionResult mapView()
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var lo = (from l in ctx.Locations
                      select l);
            if (lo.Count() == 0) { lo = null; }
            return View(lo);
        }

        public ActionResult VisitingView()
        {
            var visitCount = MainModel.visitCount();
            return View(visitCount);
        }

        public ActionResult NewsDetail(int id)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var news = ctx.News.Where(n => n.ID == id).SingleOrDefault();
            return View(news);
        }

        public ActionResult ClientNewsList(int? pageNum)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            var newslist = ctx.News.OrderByDescending(n => n.post_date);
            foreach (var news in newslist)
            {
                var index = news.body.IndexOf("</p>");
                news.body = news.body.Substring(0, index+4);
            }
            if (pageNum == null) { pageNum = 1; }
            int maxProNum = 5;
            int skipNum = (int)(maxProNum * (pageNum - 1));
            ViewBag.maxPage = (newslist.Count() - 1) / maxProNum + 1;
            ViewBag.currentPage = pageNum;
            if (newslist.Count() == 0) { return View(); }
            return View(newslist.Skip(skipNum).Take(maxProNum)); 
        }

        [HttpPost]
        public void HiddenAction(string name, string info)
        {
            DataClasses1DataContext ctx = new DataClasses1DataContext();
            HiddenTBL tbl = new HiddenTBL()
            {
                name = name,
                address = Request.UserHostAddress,
                sent_time = DateTime.Now,
                info = info
            };
            try
            {
                ctx.HiddenTBLs.InsertOnSubmit(tbl);
                ctx.SubmitChanges();
            }
            catch (Exception) { }

        }
    }
}
